/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import database_beans.Domaci;
import database_beans.Fajlovi;
import database_beans.LabVezbe;
import database_beans.Materijali;
import database_beans.PlanAngazovanja;
import database_beans.Predmet;
import database_beans.Rokovi;
import database_beans.Zaposleni;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.primefaces.event.FileUploadEvent;
import server.Log;
import server.Util;

/**
 *
 * @author stefan
 */
@ManagedBean(name = "zapCtrl")
@ViewScoped
public class ZaposleniPredmetControler implements Serializable {

    @ManagedProperty("#{userBean}")
    private UserBean user;

    private Predmet predmet;

    private ArrayList<Predmet> predmetList;

    private ArrayList<Materijali> predavanja;

    private ArrayList<Materijali> vezbe;

    private ArrayList<Rokovi> rokovi;

    private String selected;

    private int typeToAdd;

    private Materijali noviMaterijal;

    private Rokovi noviRok;

    private Fajlovi file;

    private ArrayList<LabVezbe> labVezbe;

    private ArrayList<Domaci> domaciList;

    private String[] tipMaterijala = {"", "Predavanja", "Vezbe"};

    private ArrayList<Fajlovi> fajloviLabVezba;

    private ArrayList<Fajlovi> fajloviDomaci;

    private String selectedLabVezba;

    private String selectedDomaci;

    private LabVezbe labVezba;

    private Domaci domaci;

    private boolean hasDomaci = false;

    private boolean hasLabVezba = false;

    private HashSet<Fajlovi> uploadLabVezba;

    private HashSet<Fajlovi> uploadDomaci;

    /**
     * Creates a new instance of ZaposleniPredmetControler
     */
    public ZaposleniPredmetControler() {

    }

    @PostConstruct
    public void init() {
        predmet = new Predmet();
        Zaposleni z = user.getZaposleni();

        predmetList = toList(z);
        noviMaterijal = new Materijali();
        noviRok = new Rokovi();
        predavanja = new ArrayList<>();
        vezbe = new ArrayList<>();
        labVezba = new LabVezbe();
        domaci = new Domaci();
    }

    public ArrayList<Predmet> toList(Zaposleni z) {
        if (z == null) {
            return null;
        }
        ArrayList<Predmet> list = new ArrayList<Predmet>();
        for (PlanAngazovanja p : new ArrayList<PlanAngazovanja>(z.getPlanAngazovanjas())) {
            list.add(p.getPredmet());
        }
        for (Predmet p : list) {
            Hibernate.initialize(p.getLabVezbes());
            Hibernate.initialize(p.getDomacis());
            Hibernate.initialize(p.getMaterijalis());
        }
        return list;
    }

    public Predmet getPredmet() {
        return predmet;
    }

    public void setPredmet(Predmet predmet) {
        this.predmet = predmet;
    }

    public ArrayList<Predmet> getPredmetList() {
        return predmetList;
    }

    public void setPredmetList(ArrayList<Predmet> predmetList) {
        this.predmetList = predmetList;
    }

    public UserBean getUser() {
        return user;
    }

    public void setUser(UserBean user) {
        this.user = user;
    }

    public String getSelected() {
        return selected;
    }

    public void setSelected(String selected) {
        this.selected = selected;
    }

    public ArrayList<Materijali> getPredavanja() {
        return predavanja;
    }

    public void setPredavanja(ArrayList<Materijali> predavanja) {
        this.predavanja = predavanja;
    }

    public ArrayList<Materijali> getVezbe() {
        return vezbe;
    }

    public void setVezbe(ArrayList<Materijali> vezbe) {
        this.vezbe = vezbe;
    }

    public ArrayList<Rokovi> getRokovi() {
        return rokovi;
    }

    public void setRokovi(ArrayList<Rokovi> rokovi) {
        this.rokovi = rokovi;
    }

    public int getTypeToAdd() {
        return typeToAdd;
    }

    public void setTypeToAdd(int typeToAdd) {
        this.typeToAdd = typeToAdd;
    }

    public Materijali getNoviMaterijal() {
        return noviMaterijal;
    }

    public void setNoviMaterijal(Materijali noviMaterijal) {
        this.noviMaterijal = noviMaterijal;
    }

    public Rokovi getNoviRok() {
        return noviRok;
    }

    public void setNoviRok(Rokovi noviRok) {
        this.noviRok = noviRok;
    }

    public ArrayList<LabVezbe> getLabVezbe() {
        return labVezbe;
    }

    public void setLabVezbe(ArrayList<LabVezbe> labVezba) {
        this.labVezbe = labVezba;
    }

    public ArrayList<Fajlovi> getFajloviLabVezba() {
        return fajloviLabVezba;
    }

    public void setFajloviLabVezba(ArrayList<Fajlovi> fajloviLabVezba) {
        this.fajloviLabVezba = fajloviLabVezba;
    }

    public ArrayList<Fajlovi> getFajloviDomaci() {
        return fajloviDomaci;
    }

    public void setFajloviDomaci(ArrayList<Fajlovi> fajloviDomaci) {
        this.fajloviDomaci = fajloviDomaci;
    }

    public String getSelectedLabVezba() {
        return selectedLabVezba;
    }

    public void setSelectedLabVezba(String selectedLabVezba) {
        this.selectedLabVezba = selectedLabVezba;
    }

    public String getSelectedDomaci() {
        return selectedDomaci;
    }

    public void setSelectedDomaci(String selectedDomaci) {
        this.selectedDomaci = selectedDomaci;
    }

    public ArrayList<Domaci> getDomaciList() {
        return domaciList;
    }

    public void setDomaciList(ArrayList<Domaci> domaciList) {
        this.domaciList = domaciList;
    }

    public Domaci getDomaci() {
        return domaci;
    }

    public void setDomaci(Domaci domaci) {
        this.domaci = domaci;
    }

    public LabVezbe getLabVezba() {
        return labVezba;
    }

    public void setLabVezba(LabVezbe labVezba) {
        this.labVezba = labVezba;
    }

    public boolean isHasDomaci() {
        return hasDomaci;
    }

    public void setHasDomaci(boolean hasDomaci) {
        this.hasDomaci = hasDomaci;
    }

    public boolean isHasLabVezba() {
        return hasLabVezba;
    }

    public void setHasLabVezba(boolean hasLabVezba) {
        this.hasLabVezba = hasLabVezba;
    }

    public void snimiPromene() {
        if (!"".equals(selected)) {
            Session session = Util.getSesion();
            Transaction t = session.beginTransaction();
            try {
                session.save(predmet);
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Snimljen predmet " + selected));
                t.commit();
            } catch (Exception e) {
                t.rollback();
                e.printStackTrace();
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Greska pri snimanju informacija predmeta " + selected));
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(null, "Morate odabrati predmet"));
        }
    }

    public void onChange() {
        predmet = new Predmet();
        if (!"".equals(selected)) {
            for (Predmet p : predmetList) {
                if (selected.equals(p.getNaziv())) {
                    predmet = p;
                    Log.i("Detektovana promena predmeta" + selected);
                    loadEverything();
                }
            }
        }
    }

    public void onChangeLabVezba() {
        uploadLabVezba = new HashSet<Fajlovi>();
        hasLabVezba = false;
        labVezba = new LabVezbe();
        if (!"".equals(selectedLabVezba)) {
            for (LabVezbe l : labVezbe) {
                if (selectedLabVezba.equals(l.getNaziv())) {
                    labVezba = l;
                    fajloviLabVezba = new ArrayList<>(labVezba.getFajlovis());
                    Log.i("Detektovana promena labVezbe");
                    hasLabVezba = true;
                }
            }
        }
    }

    public void onChangeDomaci() {
        uploadDomaci = new HashSet<Fajlovi>();
        hasDomaci = false;
        domaci = new Domaci();
        if (!"".equals(selectedDomaci)) {
            for (Domaci dom : domaciList) {
                if (selectedDomaci.equals(dom.getNaziv())) {
                    domaci = dom;
                    fajloviDomaci = new ArrayList<>(dom.getFajlovis());
                    Log.i("Detektovana promena projekta");
                    hasDomaci = true;
                }
            }
        }
    }

    private void loadEverything() {
        loadDomacii();
        loadIspitniZadatci();
        loadLabVezbe();
        loadMaterijali();
    }

    private void loadDomacii() {
        domaci = new Domaci();
    }

    private void loadLabVezbe() {
        labVezba = new LabVezbe();
        labVezbe = new ArrayList<>(predmet.getLabVezbes());
    }

    private void loadMaterijali() {
        predavanja = new ArrayList<>();
        ArrayList<Materijali> list = new ArrayList<>(predmet.getMaterijalis());
        while (!list.isEmpty()) {
            Materijali m = list.remove(0);
            if (m.getTip().equals(tipMaterijala[1])) {
                predavanja.add(m);
            } else {
                vezbe.add(m);
            }
        }
    }

    private void loadIspitniZadatci() {

        rokovi = new ArrayList<>(predmet.getRokovis());
    }

    public void snimiMaterijal() {

        if (!"".equals(selected)) {
            if ("".equals(noviMaterijal.getOpis())) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, null, "Morate unesti opis"));
            }
            Session session = Util.getSesion();
            Transaction t = session.beginTransaction();

            try {
                Date date = new Date(System.currentTimeMillis());
                session.save(file);
                noviMaterijal.setPredmet(predmet);
                noviMaterijal.setZaposleni(user.getZaposleni());
                noviMaterijal.setFajlovi(file);
                noviMaterijal.setTip(tipMaterijala[typeToAdd]);
                session.save(noviMaterijal);
                t.commit();
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Materijal uspesno snimljen"));
                if (typeToAdd == 1) {
                    predavanja.add(noviMaterijal);
                } else {
                    vezbe.add(noviMaterijal);
                }
            } catch (Exception e) {
                t.rollback();
                e.printStackTrace();
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Materijal nije snimljen"));
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Morate odabrati predmet"));
        }
    }

    public void uploadHandler(FileUploadEvent event) {
        file = new Fajlovi();
        file.setData(event.getFile().getContents());
        file.setNaziv(event.getFile().getFileName());
        file.setVelicina(event.getFile().getSize() / 1024);
        String fileType = event.getFile().getFileName().substring(event.getFile().getFileName().lastIndexOf(".") + 1);
        file.setTip(fileType);
        file.setDatum(new Date());
        Log.i("Upload hendler izvrsen za fajl " + event.getFile().getFileName());
    }

    public void snimiRok() {
        if (!"".equals(selected)) {
            if ("".equals(noviRok.getOpis())) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, null, "Morate unesti opis"));
            }
            Session session = Util.getSesion();
            Transaction t = session.beginTransaction();
            noviRok.setDatum(new Date());
            noviRok.setPredmet(predmet);
            try {
                session.save(file);
                noviRok.setFajlovi(file);
                session.save(noviRok);
                t.commit();
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ispitni zadatak snimljen!"));
            } catch (Exception e) {
                t.rollback();
                e.printStackTrace();
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Greska!!! Ispitni zadatak nije snimljen!"));
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Morate odabrati predmet"));
        }

    }

    public void snimiLabVezbu() {
        Session session = Util.getSesion();
        Transaction t = session.beginTransaction();
        try {
            session.update(labVezba);
            t.commit();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Laboratorijska vezba snimljena!"));
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Greska!!! Laboratorijska vezba nije snimljena!"));
        }

    }

    public void snimiDomaci() {
        Session session = Util.getSesion();
        Transaction t = session.beginTransaction();
        try {
            session.update(domaci);
            t.commit();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Domaci snimljen!"));
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Greska!!! Domaci nije snimljen!"));
        }
    }

    public void domaciUploadHandler(FileUploadEvent event) {
        Session session = Util.getSesion();
        Transaction t = session.beginTransaction();
        try {
            file = new Fajlovi();
            file.setData(event.getFile().getContents());
            file.setNaziv(event.getFile().getFileName());
            file.setVelicina(event.getFile().getSize() / 1024);
            String fileType = event.getFile().getFileName().substring(event.getFile().getFileName().lastIndexOf(".") + 1);
            file.setTip(fileType);
            file.setDatum(new Date());
            session.save(file);
            t.commit();
            uploadDomaci.add(file);
            fajloviDomaci.add(file);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload uspesan!"));
            Log.i("Upload hendler izvrsen za fajl " + event.getFile().getFileName());
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Greska!!! Upload neuspesan"));
        }
    }

    public void labVezbaUploadHandler(FileUploadEvent event) {
        Session session = Util.getSesion();
        Transaction t = session.beginTransaction();
        try {
            file = new Fajlovi();
            file.setData(event.getFile().getContents());
            file.setNaziv(event.getFile().getFileName());
            file.setVelicina(event.getFile().getSize() / 1024);
            String fileType = event.getFile().getFileName().substring(event.getFile().getFileName().lastIndexOf(".") + 1);
            file.setTip(fileType);
            file.setDatum(new Date());
            session.save(file);
            t.commit();
            uploadLabVezba.add(file);
            fajloviLabVezba.add(file);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload uspesan!"));
            Log.i("Upload hendler izvrsen za fajl " + event.getFile().getFileName());
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Greska!!! Upload neuspesan"));
        }
    }

    public void obrisiPredavanje(Materijali predavanje) {
        Session session = Util.getSesion();
        Transaction t = session.beginTransaction();
        try {
            Fajlovi f = predavanje.getFajlovi();
            session.delete(predavanje);
            //session.delete(f);
            t.commit();
            predavanja.remove(predavanje);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Brisanje uspesno!"));
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Greska!!! Brisanje neuspesno!"));
        }
    }

    public void obrisiVezbu(Materijali vezba, Fajlovi f) {
        Session session = Util.getSesion();
        Transaction t = session.beginTransaction();
        try {
            session.delete(vezba);
            //session.delete(f);
            t.commit();
            predavanja.remove(vezba);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Brisanje uspesno!"));
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Greska!!! Brisanje neuspesno!"));
        }
    }

    public void obrisiRok(Rokovi rok, Fajlovi f) {
        Session session = Util.getSesion();
        Transaction t = session.beginTransaction();
        try {
            //session.delete(f);
            session.delete(rok);
            t.commit();
            rokovi.remove(rok);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Brisanje uspesno!"));
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Greska!!! Brisanje neuspesno!"));
        }
    }

    public void obrisiLabVezbaFile(Fajlovi f) {
        Session session = Util.getSesion();
        Transaction t = session.beginTransaction();
        try {
            session.delete(f);
            t.commit();
            fajloviLabVezba.remove(f);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Brisanje uspesno!"));
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Greska!!! Brisanje neuspesno!"));
        }
    }

    public void obrisiDomaciFile(Fajlovi f) {
        Session session = Util.getSesion();
        Transaction t = session.beginTransaction();
        try {
            session.delete(f);
            t.commit();
            fajloviDomaci.remove(f);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Brisanje uspesno!"));
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Greska!!! Brisanje neuspesno!"));
        }
    }

}
